import cgi
import logging
import datetime
import wsgiref.handlers
import facebook
import random

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Greeting(db.Model):
    author = db.StringProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)

class User(db.Model):
    name = db.StringProperty()
    uid = db.IntegerProperty()
    dna = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)


class MainPage(webapp.RequestHandler):
    def post(self):
        # Both these keys are provided to you when you create a Facebook Application.
        api_key = '03bd1a3192287bdae3c21dfa0c59b889'
        secret_key = '2c64a54cd69c18401a619e744f1a5880'

        # Initialize the Facebook Object.
        self.facebookapi = facebook.Facebook(api_key, secret_key)

        url = self.facebookapi.get_add_url()
        logging.info('redirection to: %s'%url)

        # Checks to make sure that the user is logged into Facebook.
        if self.facebookapi.check_session(self.request):
            logging.info("not redirecting to app add page")
            pass
        else:
            # If not redirect them to your application add page.
            url = self.facebookapi.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"/>')
            logging.info("redirecting to app add page")
            return

        # Checks to make sure the user has added your application.
        if self.facebookapi.added:
            pass
        else:
            # If not redirect them to your application add page.
            url = self.facebookapi.get_add_url()
            self.response.out.write('<fb:redirect url="' + url + '"/>')
            return

        # Get the information about the user.
        user = self.facebookapi.users.getInfo( [self.facebookapi.uid], ['uid', 'name', 'birthday', 'relationship_status'])[0]

        # Display a welcome message to the user along with all the greetings.
        self.response.out.write("<html>")
        self.response.out.write('Hello %s,<br>' % user['name'])
        self.response.out.write('Welcome to Evopetz on Facebook.<br>')
        self.response.out.write('See your entry below.<br><br>')

        users = db.GqlQuery("SELECT * FROM User WHERE uid = :1",user['uid'])
        if users.count() == 1:
            self.response.out.write("""<center><b>Your
            Information:</b><br/>Name: <b>%s</b><br/>DNA:
            <b>%s</b><br></center>""" % (users.get().name,users.get().dna))
        elif users.count() == 0:
            self.response.out.write("""New user! Press the create button to
            start a creature!<br/>
            <form action="sign" method="post">
            <div><input type="submit" value="Create!
            </form>
            </html>""")

        else:
            self.response.out.write("Database error... too many values!")


class Guestbook(webapp.RequestHandler):
        def post(self):
                # Both these keys are provided to you when you create a Facebook Application.
            api_key = '03bd1a3192287bdae3c21dfa0c59b889'
            secret_key = '2c64a54cd69c18401a619e744f1a5880'

            # Initialize the Facebook Object.
            self.facebookapi = facebook.Facebook(api_key, secret_key)

            # Checks to make sure that the user is logged into Facebook.
            if self.facebookapi.check_session(self.request):
                pass
            else:
                # If not redirect them to your application add page.
                url = self.facebookapi.get_add_url()
                self.response.out.write('<fb:redirect url="' + url + '" />')
                return

            # Checks to make sure the user has added your application.
            if self.facebookapi.added:
                pass
            else:
                # If not redirect them to your application add page.
                url = self.facebookapi.get_add_url()
                self.response.out.write('<fb:redirect url="' + url + '" />')
                return

            # Get the information about the user.
            usr = self.facebookapi.users.getInfo( [self.facebookapi.uid], ['uid', 'name', 'birthday', 'relationship_status'])[0]

            newUser = User()
            newUser.name = usr['name']
            newUser.dna = "" + random.randint(1,10) * 'i' + random.randint(1,10) * 'o'
            newUser.uid = usr['uid']
            newUser.put()
            self.redirect('/')



application = webapp.WSGIApplication(
        [('/', MainPage),
            ('/sign', Guestbook)],
        debug=True)

def main():
    logging.getLogger().setLevel(logging.DEBUG)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
